package com.example.oneMachineLock;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * create by mwh 2021-12-16
 * cas无锁
 * cas的原理是comrareAndSet(current,update); current跟内存中的值比较，相等，就可以更新新值update。不相等则不更新新值
 * cas  1取内存数据 2当前值比较 3更新
 **/
@RestController
@RequestMapping("/casLock")
public class casLock {
    //num放外面，测试公用变量线程安全，jmeter开了50个线程，理想值：3*50=150，用Integer的每次都小于 150，atomicinteger=150
//    Integer num = new Integer(0);
    AtomicInteger num = new AtomicInteger();
    @GetMapping("/test")
    public void test() throws InterruptedException {
        test1();
        test2();
        test3();

    }

    private void test3() {
//        num++;
        num.incrementAndGet();
        System.out.println(Thread.currentThread().getName()+"snc test3"+"=========num:"+num);
    }

    private void test2() {
//        num++;
        num.incrementAndGet();
        System.out.println(Thread.currentThread().getName()+"snc test2"+"=========num:"+num);
    }

    private void test1() throws InterruptedException {
//        num++;
        num.incrementAndGet();
        System.out.println(Thread.currentThread().getName()+"snc test1"+"=========num:"+num);
//        Thread.sleep(3000);
    }

}
